package com.ltmonitor.jt808.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

import com.ltmonitor.util.Constants;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.ltmonitor.app.GlobalConfig;
import com.ltmonitor.dao.IBaseIbatisDao;
import com.ltmonitor.dao.IVehicleRecorderDao;
import com.ltmonitor.entity.BasicData;
import com.ltmonitor.entity.DriverCardRecord;
import com.ltmonitor.entity.DriverInfo;
import com.ltmonitor.entity.EWayBill;
import com.ltmonitor.entity.GPSRealData;
import com.ltmonitor.entity.GpsInfo;
import com.ltmonitor.entity.MediaItem;
import com.ltmonitor.entity.TerminalCommand;
import com.ltmonitor.entity.TerminalParam;
import com.ltmonitor.entity.VehicleData;
import com.ltmonitor.entity.VehicleRecorder;
import com.ltmonitor.jt808.model.MediaPacket;
import com.ltmonitor.jt808.protocol.IRecorderDataBlock;
import com.ltmonitor.jt808.protocol.JT_0104;
import com.ltmonitor.jt808.protocol.JT_0200;
import com.ltmonitor.jt808.protocol.JT_0201;
import com.ltmonitor.jt808.protocol.JT_0301;
import com.ltmonitor.jt808.protocol.JT_0302;
import com.ltmonitor.jt808.protocol.JT_0303;
import com.ltmonitor.jt808.protocol.JT_0500;
import com.ltmonitor.jt808.protocol.JT_0700;
import com.ltmonitor.jt808.protocol.JT_0701;
import com.ltmonitor.jt808.protocol.JT_0702;
import com.ltmonitor.jt808.protocol.JT_0702_old;
import com.ltmonitor.jt808.protocol.JT_0704;
import com.ltmonitor.jt808.protocol.JT_0800;
import com.ltmonitor.jt808.protocol.JT_0802;
import com.ltmonitor.jt808.protocol.JT_0900;
import com.ltmonitor.jt808.protocol.MuldimediaSearchDataItem;
import com.ltmonitor.jt808.protocol.ParameterItem;
import com.ltmonitor.jt808.protocol.PostitionAdditional_InOutAreaAlarmAdditional;
import com.ltmonitor.jt808.protocol.PostitionAdditional_OverSpeedAlarmAdditional;
import com.ltmonitor.jt808.protocol.PostitionAdditional_RouteDriveTimeAlarmAdditional;
import com.ltmonitor.jt808.protocol.Recorder_DoubtfulPointData;
import com.ltmonitor.jt808.protocol.Recorder_SpeedIn2Days;
import com.ltmonitor.jt808.protocol.Recorder_SpeedIn360Hours;
import com.ltmonitor.jt808.protocol.Recorder_TiredDrivingRecord;
import com.ltmonitor.jt808.protocol.T808Message;
import com.ltmonitor.jt808.protocol.T808MessageHeader;
import com.ltmonitor.jt808.protocol.TiredDrivingRecordItem;
import com.ltmonitor.jt808.service.IAlarmService;
import com.ltmonitor.jt808.service.ICommandParseService;
import com.ltmonitor.jt808.service.IGpsDataService;
import com.ltmonitor.jt808.service.IMediaService;
import com.ltmonitor.jt808.service.ITransferGpsService;
import com.ltmonitor.jt808.tool.Tools;
import com.ltmonitor.jt809.entity.DriverModel;
import com.ltmonitor.service.IBasicDataService;
import com.ltmonitor.service.IBatchInsertService;
import com.ltmonitor.service.IDriverCardRecordService;
import com.ltmonitor.service.IDriverInfoService;
import com.ltmonitor.service.IEWayBillService;
import com.ltmonitor.service.ILocationService;
import com.ltmonitor.service.IMediaItemService;
import com.ltmonitor.service.IRealDataService;
import com.ltmonitor.service.ITerminalCommandService;
import com.ltmonitor.service.ITerminalParamService;
import com.ltmonitor.service.IVehicleRecorderService;
import com.ltmonitor.service.JT808Constants;
import com.ltmonitor.util.DateUtil;
import com.ltmonitor.util.StringUtil;
import com.ltmonitor.vo.GnssData;

@Service("gpsDataService")
public class GpsDataService implements IGpsDataService {
	public static String TURN_ON = "1"; // 报警开
	public static String TURN_OFF = "0"; // 报警关闭

	private static Logger logger = Logger.getLogger(GpsDataService.class);
	private ConcurrentLinkedQueue<T808Message> dataQueue = new ConcurrentLinkedQueue();

	/**
	 * 线程池，默认是50个
	 */
	ExecutorService fixedThreadPool = Executors.newFixedThreadPool(50);
	// 实时数据缓存
	public ConcurrentMap<String, GPSRealData> realDataMap = new ConcurrentHashMap<String, GPSRealData>();

	/*
	 * 信息点播，存放终端卡号和点播类型ID的映射关系 系统定时调取更信息类的信息，下发给请求点播的终端
	 */
	private ConcurrentHashMap<String, List<Integer>> inforIdMap = new ConcurrentHashMap<String, List<Integer>>();

	@Value("#{config.enableSaveDb}")
	private Boolean enableSaveDb;

	private Boolean startProcess = true;

	@Autowired
	private ICommandParseService commandParseService;

	@Autowired
	private ITerminalCommandService terminalCommandService;
	// 数据转发服务,主要用于809转发
	@Autowired
	private ITransferGpsService transferGpsService;
	@Autowired
	IBaseIbatisDao baseIbatisDao;

	@Autowired
	private IMediaItemService mediaItemService;

	@Autowired
	private IDriverInfoService driverInfoService;

	@Autowired
	private IEWayBillService eWayBillService;
	@Autowired
	private IDriverCardRecordService driverCardRecordService;

	@Autowired
	private IVehicleRecorderService vehicleRecorderService;

	@Autowired
	private ITerminalParamService terminalParamService;

	/**
	 * 媒体拍照数据接收和提取服务
	 */
	@Autowired
	private IMediaService mediaService;
	/**
	 * 实时数据服务
	 */
	@Resource
	private IRealDataService realDataService;
	/**
	 * 静态车辆信息服务,提供获取车辆信息的数据
	 */
	// private IVehiclezService vehicleService;
	/**
	 * 定时大批量插入历史gps数据入库服务
	 */
	@Autowired
	private IBatchInsertService batchInsertService;
	/**
	 * 根据坐标获取地址信息的服务
	 */
	@Autowired
	private ILocationService locationService;

	/**
	 * 信息点播线程，不断的根据终端点播的信息类型，将数据库对应类型的信息，下发给终端
	 */
	private Thread vodThread;
	/**
	 * 是否接收并处理透传数据
	 */
	@Value("#{config.transparentTransport}")
	private boolean transparentTransport;
	/**
	 * 实时数据数据处理线程
	 */
	private Thread processRealDataThread;
	// 报警分析服务，分析定位数据，生成报警记录
	@Autowired
	private IAlarmService alarmService;
	/**
	 * 基础服务，主要是获得要给终端发布的信息数据
	 */
	@Autowired
	private IBasicDataService basicDataService;
	/**
	 * 行驶记录仪版本 2003,2012两种,默认是2003
	 */
	private String vehicleRecorderVersion;
	/**
	 * 启用驾驶员信息上传 (部标检测时启用，正式运用时关闭)
	 */
	@Value("#{config.enableDriverInfoUpload}")
	private boolean enableDriverInfoUpload;
	/**
	 * 启用电子运单上传 (部标检测时启用，正式运用时关闭)
	 */
	@Value("#{config.enableEWayBillUpload}")
	private boolean enableEWayBillUpload;


	public GpsDataService() {
		// setUploadDir("d:\\media\\");

	}

	public void start() {
		alarmService.start();

		processRealDataThread = new Thread(new Runnable() {
			public void run() {
				ProcessRealDataThreadFunc();
			}
		});
		processRealDataThread.start();

		vodThread = new Thread(new Runnable() {
			public void run() {
				vodThreadFunc();
			}
		});
		vodThread.start();

	}

	public void stopService() {
		startProcess = false;
		try {
			processRealDataThread.join(20000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		this.alarmService.stopService();
	}

	private String uploadDir;

	public final String getUploadDir() {
		return uploadDir;
	}

	public final void setUploadDir(String value) {
		uploadDir = value;
	}

	// 是否是新808
	private String isNew808;

	public final String getIsNew808() {
		return isNew808;
	}

	public final void setIsNew808(String value) {
		isNew808 = value;
	}

	/**
	 * 在spring初始化时调用，在applicationContext-jt808.xml中配置此方法
	 */
	public void init() {
		// this.resetGpsOnlineState();
	}

	// 将所有车辆的状态设置为false
	public final void resetGpsOnlineState() {
		try {
			this.baseIbatisDao.update("resetRealDataState", new HashMap());
		} catch (RuntimeException ex) {
			logger.error(ex.getMessage(), ex);
		}
	}

	// 保存终端参数
	private void SaveTerminalParam(T808Message msg) {
		JT_0104 ParamMessage = (JT_0104) msg.getMessageContents();
		if (ParamMessage == null)
			return;
		int sn = ParamMessage.getResponseMessageSerialNo();
		TerminalCommand tc = this.terminalCommandService.getCommandBySn(sn);// (TerminalCommand)this.baseDao.find(hsql,
		// resNo);
		long commandId = 0;
		if (tc != null) {
			commandId = tc.getEntityId();
		}

		for (ParameterItem pi : ParamMessage.getParameters()) {
			try {
				String paramCode = "0x"
						+ Tools.ToHexString(pi.getParameterId(), 2)
								.toUpperCase();
				String hql = "from TerminalParam where simNo = ? and code = ?";
				TerminalParam tp = (TerminalParam) terminalParamService.find(
						hql, new Object[] { msg.getHeader().getSimId(),
								paramCode });
				if (tp == null) {
					tp = new TerminalParam();
				}
				tp.setSimNo(msg.getHeader().getSimId());
				tp.setCode(paramCode);
				tp.setValue("" + pi.getParameterValue());
				tp.setFieldType("" + pi.getParameterLength());
				tp.setUpdateDate(new java.util.Date());
				tp.setCommandId(commandId);
				tp.setSN(ParamMessage.getResponseMessageSerialNo()); // 对应平台流水号
				terminalParamService.saveOrUpdate(tp);
				// result.Add(tp);
			} catch (RuntimeException ex) {
				logger.error(ex.getMessage(), ex);
			}

		}

		if (tc != null) {
			commandId = tc.getEntityId();
			commandParseService.UpdateStatus(msg.getSimNo(), sn,
					TerminalCommand.STATUS_SUCCESS);
		}
	}

	/**
	 * 转发实时数据 获取实时数据后，通过调用转发服务,将数据以809格式转发出去
	 * 
	 * @param rd
	 * @param gi
	 */
	public void transfer(GPSRealData rd, GpsInfo gi) {
		if (transferGpsService == null
				|| this.transferGpsService.isTransferTo809Enabled() == false)
			return;

		GnssData gd = new GnssData();
		gd.setAltitude((int) (rd.getAltitude()));
		gd.setDirection(rd.getDirection());
		gd.setGpsSpeed((int) (rd.getVelocity()));
		gd.setLatitude((int) (rd.getLatitude() * 1000000));
		gd.setLongitude((int) (rd.getLongitude() * 1000000));
		gd.setPlateNo(rd.getPlateNo());
		gd.setTotalMileage((int) (rd.getMileage()));
		gd.setDirection(rd.getDirection());
		gd.setRecSpeed((int) rd.getRecordVelocity());
		long alarmState = Long.valueOf(rd.getAlarmState(), 2);
		// gd.setAlarmState(alarmState);
		gd.setAlarmState(gi.getAlarmState());
		// gd.setAlarmState(2);
		long intStatus = Long.valueOf(rd.getStatus(), 2);
		gd.setVehicleState(intStatus);
		gd.setVehicleState(gi.getStatus());
		gd.setPosTime(rd.getSendTime());

		VehicleData vd = this.realDataService.getVehicleData(rd.getSimNo());
		if (vd != null)
			gd.setPlateColor(vd.getPlateColor());

		transferGpsService.transfer(gd);
	}

	// 处理GPS数据
	public final void ProcessMessage(T808Message message) {
		int headerType = message.getHeader().getMessageType();
		if (headerType == 0x0002
				|| headerType == 0x0001 // 心跳 -
				|| headerType == 0x0000
				|| headerType == 0x0100 // 注册
				|| headerType == 0x0003 // 终端注销
				|| headerType == 0x0102 || headerType == 0x0f46
				|| headerType == 0x0f45) // 鉴权 - -
		{
			// 非数据包，不进行处理
			return;
		}
		

		dataQueue.add(message);
	}

	
	
	

	/**
	 * 信息点播线程，根据终端上传的点播请求，从数据库中读取对应信息类型的内容，不断的下发给请求的终端。
	 */
	private void vodThreadFunc() {
		while (true) {
			if (inforIdMap.isEmpty() == false) {
				Set<String> keys = this.inforIdMap.keySet();
				for (String simNo : keys) {
					VehicleData vd = this.realDataService.getVehicleData(simNo);
					List<Integer> inforIds = inforIdMap.get(simNo);
					if (inforIds != null) {
						for (Integer inforId : inforIds) {
							if (GlobalConfig.infoMenuIdMap.containsKey(inforId) == false)
							{
								logger.error("该点播不存在:" + inforId);
								continue;
							}
							List<BasicData> bdList = this.basicDataService
									.getInformationByType("" + inforId);
							for (BasicData information : bdList) {
								// 信息下发
								TerminalCommand tc = new TerminalCommand();
								tc.setCmdType(JT808Constants.CMD_INFORMATION);
								// int configType = info;
								String content = "";
								tc.setCmdData(inforId + ";"
										+ information.getName());
								tc.setSimNo(simNo);
								tc.setPlateNo(vd.getPlateNo());
								tc.setOwner("timer");
								tc.setCmd("" + inforId);
								this.terminalCommandService.save(tc);
							}
						}
					}
				}
			}
			try {
				Thread.sleep(1000 * 20 * 1);
			} catch (InterruptedException e) {
				e.printStackTrace();
				break;
			}
		}
	}

	private void ProcessRealDataThreadFunc() {

		 try {
			 for (int m = 0; m < 4; m++) {
				 Date nextDay =
						 DateUtil.getDate(new Date(), Calendar.DAY_OF_YEAR, m);
				 String
						 tableName = "gpsInfo" + DateUtil.toStringByFormat(nextDay,
						 "yyyyMMdd");
				 baseIbatisDao.createGpsInfoTableIfNotExist(tableName);
			 }
		 } catch (Exception ex) {
		 	logger.error(ex.getMessage(), ex);
		 }
		try {
			String alarmTableName = Constants.getAlarmTableName();
			baseIbatisDao.createNewAlarmTableIfNotExist(alarmTableName);
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}


		while (startProcess) {
			try {
				int queueNum = dataQueue.size();
				T808Message tm = dataQueue.poll();

				if (queueNum > 1000) {
					logger.error("实时消息队列处理速度慢,排队数量:" + queueNum);
					if (tm == null) {
						logger.error("队列错误");
					}
				}

				 final List<GpsInfo> gpsInfoList = new ArrayList<GpsInfo>();
				int m = 0;
				Date startDate = new Date();
				while (tm != null) {
					int headerType = tm.getMessageType();
					// 定位数据
					if (headerType == 0x0200 || headerType == 0x0201) {
						GpsInfo gi = this.processLocationPacket(tm);
						if (gi != null) {
							 gpsInfoList.add(gi);
							this.batchInsertService.enQueue(gi);
						}
					} else
						processData(tm);
					if (m++ > 200)
						break;
					tm = dataQueue.poll();
				}

				 if (gpsInfoList.size() > 0) {
				 this.batchInsertService.enQueue(gpsInfoList);
				 }

				Date endDate = new Date();
				double sec = DateUtil.getSeconds(startDate, endDate);
				if (sec > 0.5) {
					logger.error(m + "条协议数据处理耗时:" + sec);
				}
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
			try {
				Thread.sleep(10L);
			} catch (InterruptedException e1) {
			}
		}
	}

	/**
	 * 收到808消息后，根据消息的不同，进行不同的处理
	 * 
	 * @param message
	 */
	private void processData(T808Message message) {
		int headerType = message.getHeader().getMessageType();
		String simNo = message.getSimNo();
		if (headerType == 0x0104) {
			// 查询参数返回的应答参数数据存入数据库中
			SaveTerminalParam(message);
			return;
		} else if (headerType == 0x0801) {
			// 媒体上传数据
			// SaveMedia(message);
			// 交给媒体上传服务处理
			mediaService.processMediaMsg(message);
		} else if (headerType == 0x0800) {
			// 媒体信息上传数据
			SaveMediaInfo(message);
		} else if (headerType == 0x0802) {
			// 媒体检索数据
			this.SaveMediaSearchItem(message);
		} else if (headerType == 0x0700) {
			// 行车记录仪数据
			SaveVehicleRecorder(message);
		} else if (headerType == 0x0500) {
			JT_0500 answerData = (JT_0500) message.getMessageContents();
			JT_0200 p = answerData.getPositionReport();
			GpsInfo gi = this.processBatchLocationPacket(simNo, p);
			GPSRealData rd = this.realDataService.get(simNo);
			if (rd == null)
				return;
			if (gi.getLatitude() > 0 && gi.getLongitude() > 0) {
				// 保证是有效坐标
				rd.setLatitude(gi.getLatitude());
				rd.setLongitude(gi.getLongitude());
			}
			rd.setSendTime(gi.getSendTime());
			if (rd.getVelocity() > 0 && gi.getVelocity() == 0) {
				// 停车时，保存最近一次停车时间
				rd.setParkingTime(rd.getSendTime());
			}

			rd.setVelocity(gi.getVelocity());
			rd.setSignalState(gi.getSignalState());
			rd.setDirection(gi.getDirection());
			rd.setStatus(p.getStrStatus());
			rd.setAlarmState(p.getStrWarn());
			rd.setMileage(gi.getMileage());
			rd.setVelocity(gi.getVelocity());
			rd.setOnline(true);
			rd.setRecordVelocity(gi.getRecordVelocity());
			rd.setAltitude(gi.getAltitude());
			rd.setValid(gi.isValid());
			rd.setGas(gi.getGas());
			rd.setOnline(true);
		} else if (headerType == 0x0704) {
			// 定位补报，需要将补报的定位信息批量入库
			JT_0704 rd = (JT_0704) message.getMessageContents();
			List<JT_0200> packetList = rd.getPositionReportList();
			for (JT_0200 p : packetList) {
				this.processBatchLocationPacket(simNo, p);
			}
		} else if (headerType == 0x0701 && this.enableEWayBillUpload) {
			// 电子运单数据
			saveEWayBill(message);

			JT_0701 rd = (JT_0701) message.getMessageContents();
			TerminalCommand tc = new TerminalCommand();
			tc.setCmdType(headerType);
			tc.setSN(message.getHeader().getMessageSerialNo());
			tc.setSimNo(message.getSimNo());
			VehicleData vd = this.realDataService.getVehicleData(tc.getSimNo());
			if (vd != null) {
				tc.setPlateNo(vd.getPlateNo());
				tc.setVehicleId(vd.getEntityId());
			}
			tc.setCmdData(rd.getElectronicFreightContent());
			tc.setOwner(TerminalCommand.FROM_TERMINAL);
			tc.setUpdateDate(new Date());
			tc.setStatus(TerminalCommand.STATUS_SUCCESS);

			this.terminalCommandService.save(tc);

		} else if (headerType == 0x0702 && this.enableDriverInfoUpload) {
			// 驾驶员主动上报信息
			this.saveDriver(message);
			JT_0702 rd = (JT_0702) message.getMessageContents();
			if (rd == null)
				return;
			TerminalCommand tc = new TerminalCommand();
			tc.setCmdType(headerType);
			tc.setSN(message.getHeader().getMessageSerialNo());
			tc.setSimNo(message.getSimNo());
			VehicleData vd = this.realDataService.getVehicleData(tc.getSimNo());
			if (vd != null) {
				tc.setPlateNo(vd.getPlateNo());
				tc.setVehicleId(vd.getEntityId());
			}
			tc.setCmdData(rd.toString());
			tc.setOwner(TerminalCommand.FROM_TERMINAL);
			tc.setUpdateDate(new Date());
			tc.setStatus(TerminalCommand.STATUS_SUCCESS);

			this.terminalCommandService.save(tc);
		} else if (headerType == 0x0302) {
			// 终端对提问下发指令的应答
			JT_0302 ack = (JT_0302) message.getMessageContents();
			int responseNo = ack.getResponseMessageSerialNo();
			int answerId = ack.getAnswerId();
			String answer = "不存在";

			String hsql = "from TerminalCommand where SN = ? and createDate > ? order by createDate desc";
			Date startDate = DateUtil.getDate(new Date(), Calendar.HOUR_OF_DAY,
					-1);
			TerminalCommand oldTc = (TerminalCommand) this.terminalCommandService
					.find(hsql, new Object[] { (long) responseNo, startDate });

			// 需要找到以前提问下发的候选答案，来判断提问应答的是否正确
			int rightAnswerId = -1;
			if (oldTc != null && oldTc.getRemark() != null) {
				String[] fields = oldTc.getCmdData().split("[;]", -1);
				rightAnswerId = Integer.parseInt(oldTc.getRemark());
				for (String field : fields) {
					if (StringUtil.isNullOrEmpty(field)) {
						continue;
					}
					String[] items = field.split("[,]", -1);
					if (items.length == 2) {
						int id = Integer.parseInt(items[0]);
						String answerOption = items[1];
						if (answerId == id) {
							answer = answerOption;
							break;
						}
					}
				}
			}
			String answerResult = rightAnswerId == answerId ? "正确" : "错误";
			TerminalCommand tc = new TerminalCommand();
			tc.setCmdType(headerType);
			tc.setSN(message.getHeader().getMessageSerialNo());
			tc.setSimNo(message.getSimNo());
			VehicleData vd = this.realDataService.getVehicleData(tc.getSimNo());
			if (vd != null) {
				tc.setPlateNo(vd.getPlateNo());
				tc.setVehicleId(vd.getEntityId());
			}
			tc.setCmdData("选择ID是:" + answerId + ",回答内容是:" + answer + ",回答:"
					+ answerResult);
			tc.setOwner(TerminalCommand.FROM_TERMINAL);
			tc.setUpdateDate(new Date());
			tc.setStatus(TerminalCommand.STATUS_SUCCESS);

			this.terminalCommandService.save(tc);

		} else if (headerType == 0x0303) {
			// 点播信息的应答
			JT_0303 ack = (JT_0303) message.getMessageContents();
			int inforType = ack.getMessageType(); // 点播的信息类型 ID
			int req = ack.getPointResult();// 0：取消；1：点播

			if (req == 0) {
				// 取消点播，需要在去除缓存，避免再次发送信息
				List<Integer> inforTypes = this.inforIdMap.get(message
						.getSimNo());
				if (inforTypes != null) {
					for (int m = 0; m < inforTypes.size(); m++) {
						if (inforTypes.get(m) == inforType)
							inforTypes.remove(m);
					}
					// this.inforIdMap.remove(message.getSimNo());
				}
			} else {
				// 放于内存中，进行定时下发点播信息
				List<Integer> inforTypes = this.inforIdMap.get(message
						.getSimNo());
				if (inforTypes == null) {
					inforTypes = new ArrayList<Integer>();
					this.inforIdMap.put(message.getSimNo(), inforTypes);
				}
				if (inforTypes.contains(inforType) == false)
					inforTypes.add(inforType);
			}
			try {
				TerminalCommand tc = new TerminalCommand();
				tc.setCmdType(headerType);
				tc.setSN(message.getHeader().getMessageSerialNo());
				tc.setSimNo(message.getSimNo());
				VehicleData vd = this.realDataService.getVehicleData(tc
						.getSimNo());
				if (vd != null) {
					tc.setPlateNo(vd.getPlateNo());
					tc.setVehicleId(vd.getEntityId());
				}
				String strReq = req == 0 ? "终端取消点播" : "终端请求点播";
				strReq += ",信息类型ID是:" + inforType;
				if (GlobalConfig.infoMenuIdMap.containsKey(inforType) == false) {
					strReq += ",该信息类型ID不存在";
				} else {
					strReq += ",菜单名:"
							+ GlobalConfig.infoMenuIdMap.get(inforType);
				}
				tc.setCmdData(strReq);
				tc.setOwner(TerminalCommand.FROM_TERMINAL);
				tc.setUpdateDate(new Date());
				tc.setStatus(TerminalCommand.STATUS_SUCCESS);

				this.terminalCommandService.save(tc);
			} catch (Exception ex) {
				logger.error(ex.getMessage(), ex);
			}
		} else if (headerType == 0x0301) {
			// 终端事件上报
			JT_0301 ack = (JT_0301) message.getMessageContents();
			int eventId = ack.getEventId();

			TerminalCommand tc = new TerminalCommand();
			tc.setCmdType(headerType);
			tc.setSN(message.getHeader().getMessageSerialNo());
			tc.setSimNo(message.getSimNo());
			tc.setUpdateDate(new Date());
			VehicleData vd = this.realDataService.getVehicleData(tc.getSimNo());
			if (vd != null) {
				tc.setPlateNo(vd.getPlateNo());
				tc.setVehicleId(vd.getEntityId());
			}
			String eventContent = this.commandParseService
					.getEventContent(eventId);
			if (eventContent == null) {
				eventContent = "该事件ID不存在";
			} else
				eventContent = "事件内容:" + eventContent;
			tc.setCmdData("事件ID是:" + eventId + "," + eventContent);
			tc.setOwner(TerminalCommand.FROM_TERMINAL);
			tc.setStatus(TerminalCommand.STATUS_SUCCESS);

			this.terminalCommandService.save(tc);
		} else if (headerType == 0x0900 && isTransparentTransport()) {
			// 终端对平台的上行透传
			JT_0900 ack = (JT_0900) message.getMessageContents();
			int msgType = ack.getMessageType();
			String msg = new String(ack.getMessageContent());

			TerminalCommand tc = new TerminalCommand();
			tc.setCmdType(0x0900);
			tc.setSN(message.getHeader().getMessageSerialNo());
			tc.setSimNo(message.getSimNo());
			tc.setUpdateDate(new Date());
			VehicleData vd = this.realDataService.getVehicleData(tc.getSimNo());
			if (vd != null) {
				tc.setPlateNo(vd.getPlateNo());
				tc.setVehicleId(vd.getEntityId());
			}
			tc.setCmdData("透传类型是:" + msgType + ",透传数据：" + msg);
			tc.setOwner("");
			tc.setStatus(TerminalCommand.STATUS_SUCCESS);

			this.terminalCommandService.save(tc);

		} else
			logger.error("未知的处理类型:" + Integer.toHexString(headerType));

	}

	private GpsInfo processLocationPacket(T808Message message) {
		if (message.getHeader() == null)
			return null;
		int headerType = message.getHeader().getMessageType();
		JT_0200 jvi = null;
		if (headerType == 0x0200) {
			jvi = (JT_0200) message.getMessageContents();
		} else if (headerType == 0x0201) {
			JT_0201 jt = (JT_0201) message.getMessageContents();
			jvi = jt.getPositionReport();
		}

		if (jvi == null)
			return null;
		Date dt = DateUtil.stringToDatetime(jvi.getTime(),
				"yyyy-MM-dd HH:mm:ss");
		if (dt == null) {
			logger.error(message.getSimNo() + "," + message.getPlateNo()
					+ "定位包无效的日期:" + jvi.getTime());
			return null; // 对于无效日期的包，是否丢弃?
		}
		java.util.Date now = new java.util.Date();
		// 发送的旧数据,无效乱数据
		if (Math.abs(DateUtil.getDay(dt, now)) >= 4) {
			// logger.error("定位数据日期无效:" + message.getSimNo() + ",定位包信息:" +
			// jvi.toString());
			return null;
		}

		GpsInfo gi = new GpsInfo();
		gi.setSendTime(dt);
		gi.setPlateNo(message.getPlateNo());
		gi.setSimNo(message.getHeader().getSimId());
		gi.setLatitude(0.000001 * jvi.getLatitude());
		gi.setLongitude(0.000001 * jvi.getLongitude());
		short speed = jvi.getSpeed();
		gi.setVelocity(speed / 10.0);
		short direction = jvi.getCourse();
		gi.setDirection(direction);
		gi.setStatus(jvi.getStatus());
		gi.setAlarmState(jvi.getAlarmFlag());
		gi.setMileage(0.1 * jvi.getMileage());
		gi.setGas(0.1 * jvi.getOil());
		gi.setRecordVelocity(0.1 * jvi.getRecorderSpeed());
		gi.setValid(jvi.isValid());
		gi.setAltitude(jvi.getAltitude());
		gi.setRecordVelocity(0.1 * jvi.getRecorderSpeed());
		gi.setSignalState(jvi.getSignal());

		GPSRealData rd = realDataService.get(gi.getSimNo());
		if (rd == null) {
			// logger.error("发现没有注册的车辆, simNo:" + gi.getSimNo());
			return null;
		}
		rd.setResponseSn((int) (message.getHeader().getMessageSerialNo()));

		// 附加扩展位的解析
		if (jvi.getInOutAreaAlarmAdditional() != null) {
			// 进出区域报警
			PostitionAdditional_InOutAreaAlarmAdditional additional = jvi
					.getInOutAreaAlarmAdditional();
			rd.setAreaAlarm(additional.getDirection());
			rd.setAreaId(additional.getAreaId());
			rd.setAreaType(additional.getPositionType());
		} else {
			// 区域报警清空
			rd.setAreaAlarm(0);
			rd.setAreaId(0);
			rd.setAreaType(0);
		}
		if (jvi.getOverSpeedAlarmAdditional() != null) {
			// 超速报警
			PostitionAdditional_OverSpeedAlarmAdditional additional = jvi
					.getOverSpeedAlarmAdditional();
			rd.setOverSpeedAreaId(additional.getAreaId());
			rd.setOverSpeedAreaType(additional.getPositionType());
		} else {
			// 区域报警清空
			rd.setOverSpeedAreaId(0);
			rd.setOverSpeedAreaType(0);
		}
		if (jvi.getRouteTimeAlarmAdditional() != null) {
			// 路段行驶时间不足或过长报警
			PostitionAdditional_RouteDriveTimeAlarmAdditional additional = jvi
					.getRouteTimeAlarmAdditional();
			rd.setRouteAlarmType(additional.getResult());
			rd.setRouteSegmentId(additional.getRouteId());
			rd.setRunTimeOnRoute(additional.getDriveTime());
		} else {
			// 区域报警清空
			rd.setRouteAlarmType(0);
			rd.setRouteSegmentId(0);
			rd.setRunTimeOnRoute(0);
		}

		gi.setPlateNo(rd.getPlateNo());
		gi.setVehicleId(rd.getVehicleId());
		gi.setLocation(rd.getLocation());
		message.setPlateNo(rd.getPlateNo());
		rd.setSendTime(gi.getSendTime());
		try {
			if (gi.getLatitude() > 0 && gi.getLongitude() > 0) {
				// 保证是有效坐标
				rd.setLatitude(gi.getLatitude());
				rd.setLongitude(gi.getLongitude());
			}
			rd.setSendTime(gi.getSendTime());
			if ((rd.getParkingTime() == null || rd.getVelocity() > 0)
					&& gi.getVelocity() == 0) {
				// 停车时，保存最近一次停车时间
				rd.setParkingTime(rd.getSendTime());
			}
			rd.setVelocity(gi.getVelocity());
			rd.setSignalState(gi.getSignalState());
			rd.setDirection(gi.getDirection());
			rd.setStatus(jvi.getStrStatus());
			rd.setAlarmState(jvi.getStrWarn());
			rd.setMileage(gi.getMileage());
			if (rd.getLastDayMileage() == -1) {
				rd.setLastDayMileage(rd.getMileage());
			}
			rd.setVelocity(gi.getVelocity());
			rd.setOnline(true);
			rd.setRecordVelocity(gi.getRecordVelocity());
			rd.setAltitude(gi.getAltitude());
			rd.setValid(jvi.isValid());
			rd.setGas(gi.getGas());
			rd.setOnline(true);
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}

		try {
			transfer(rd, gi); // 转发服务
			alarmService.processRealData(rd);// 报警服务
			if (Tools.isNullOrEmpty(rd.getPlateNo()) == false) {
				realDataService.update(rd);
			}
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}

		gi.setPlateNo(rd.getPlateNo()); // 保持车牌号一致

		return gi;
	}

	private GpsInfo processBatchLocationPacket(String simNo, JT_0200 jvi) {
		Date dt = DateUtil.stringToDatetime(jvi.getTime(),
				"yyyy-MM-dd HH:mm:ss");
		if (dt == null) {
			// logger.error(gi.getSimNo() + "," + message.getPlateNo()
			// + "定位包无效的日期:" + jvi.getTime());
			// return; // 对于无效日期的包，是否丢弃?
		}
		java.util.Date now = new java.util.Date();
		// 发送的旧数据,无效乱数据
		if (DateUtil.getDay(dt, now) >= 100 || DateUtil.getDay(now, dt) > 1) {
			// logger.error("定位数据日期无效:" + simNo + ",定位包信息:" + jvi.toString());
			return null;
		}

		GpsInfo gi = new GpsInfo();
		gi.setSimNo(simNo);
		gi.setLatitude(0.000001 * jvi.getLatitude());
		gi.setLongitude(0.000001 * jvi.getLongitude());
		short speed = jvi.getSpeed();
		gi.setVelocity(0.1 * speed);
		short direction = jvi.getCourse();
		gi.setDirection(direction);
		gi.setStatus(jvi.getStatus());
		gi.setAlarmState(jvi.getAlarmFlag());
		gi.setMileage(0.1 * jvi.getMileage());
		gi.setGas(0.1 * jvi.getOil());
		gi.setRecordVelocity(0.1 * jvi.getRecorderSpeed());
		gi.setValid(jvi.isValid());
		gi.setAltitude(jvi.getAltitude());
		gi.setRecordVelocity(0.1 * jvi.getRecorderSpeed());

		gi.setSendTime(dt);

		GPSRealData rd = realDataService.get(gi.getSimNo());// getRealDataBySimNo(gi.getSimNo());
		if (rd == null) {
			// logger.error("发现没有注册的车辆, simNo:" + gi.getSimNo());
			// return;
		} else
			gi.setPlateNo(rd.getPlateNo());
		// message.setPlateNo(rd.getPlateNo());

		// 保存定位数据到历史轨迹表中
		try {
			Date today = new Date();
			Date nextDay = DateUtil.getDate(today, 1);
			if (gi.getSendTime().compareTo(nextDay) < 0) {
				this.batchInsertService.enQueue(gi);

			}
		} catch (RuntimeException ex) {
			logger.error(ex.getMessage());
			logger.error(ex.getStackTrace());
		}

		return gi;
	}

	/**
	 * 电子运单数据入库
	 * 
	 * @param msg
	 */
	private void saveEWayBill(T808Message msg) {

		JT_0701 rd = (JT_0701) msg.getMessageContents();
		VehicleData vd = this.realDataService.getVehicleData(msg.getSimNo());
		if (vd != null) {
			String hql = "from EWayBill where VehicleId = ?";
			EWayBill ebill = (EWayBill) this.eWayBillService.find(hql,
					vd.getEntityId());
			if (ebill == null)
				ebill = new EWayBill();
			ebill.seteContent(rd.getElectronicFreightContent());
			ebill.setPlateNo(vd.getPlateNo());
			ebill.setVehicleId(vd.getEntityId());
			ebill.setPlateColor(vd.getPlateColor());
			// 转发电子运单
			this.transferGpsService.transfer(ebill);
			this.eWayBillService.saveOrUpdate(ebill);
		}

	}

	/**
	 * 驾驶员上报信息，入库，同时转发给上级平台
	 * 
	 * @param msg
	 */
	private void saveDriver(T808Message msg) {

		JT_0702 driverData = (JT_0702) msg.getMessageContents();
		if (driverData == null)
			return;
		JT_0702_old oldDriverData = driverData.getOldDriverData();
		VehicleData vd = this.realDataService.getVehicleData(msg.getSimNo());
		if (vd == null)
			return;

		String hql = "from DriverInfo where vehicleId = ? and deleted = ?";
		DriverInfo driver = (DriverInfo) this.driverInfoService.find(hql,
				new Object[] { vd.getEntityId(), false });
		if (driver == null) {
			driver = new DriverInfo();
			driver.setVehicleId(vd.getEntityId());
			driver.setMainDriver(true);
		}
		if (vd != null) {
			if (oldDriverData != null) {
				if (this.enableDriverInfoUpload) {
					try {
						driver.setDriverName(oldDriverData.getDriverName());
						driver.setLicenseAgency(oldDriverData.getAgencyName());// 发证机构
						driver.setDriverLicence(oldDriverData
								.getCertificationCode());// 从业资格证编码
						driver.setIdentityCard(oldDriverData.getDriverID());// 身份证编码
						driver.setMainDriver(true);
						this.driverInfoService.saveOrUpdate(driver);
					} catch (Exception ex) {
						logger.error(ex.getMessage(), ex);
					}
				}

				DriverModel d = new DriverModel();
				d.setPlateNo(vd.getPlateNo());
				d.setPlateColor(vd.getPlateColor());
				d.setDriverId(oldDriverData.getDriverID());
				d.setDriverName(oldDriverData.getDriverName());
				d.setLicense(oldDriverData.getCertificationCode());
				d.setOrgName(oldDriverData.getAgencyName());
				// 主动上报驾驶员信息
				this.transferGpsService.transferDriverInfo(d);
			} else {
				if (this.enableDriverInfoUpload) {
					try {
						driver.setDriverName(driverData.getDriverName());
						driver.setLicenseAgency(driverData.getAgencyName());// 发证机构
						driver.setDriverLicence(driverData
								.getCertificationCode());// 从业资格证编码
						// driver.setIdentityCard(driverData.getDriverID());//
						// 身份证编码
						this.driverInfoService.saveOrUpdate(driver);
					} catch (Exception ex) {
						logger.error(ex.getMessage(), ex);
					}
				}

				try {
					DriverCardRecord r = new DriverCardRecord();
					r.setAgencyName(driverData.getAgencyName());
					r.setCardState(driverData.getCardState());
					r.setCertificationCode(driverData.getCertificationCode());
					r.setDriverName(driverData.getDriverName());
					r.setReadResult(driverData.getReadResult());
					r.setVehicleId(vd.getEntityId());
					Date operTime = DateUtil.toDateByFormat(
							driverData.getOperTime(), "yyyy-MM-dd hh:mm:ss");
					r.setOperTime(operTime);
					r.setValidateDate(driverData.getValidateDate());
					this.driverCardRecordService.saveOrUpdate(r);
				} catch (Exception ex) {
					logger.error(ex.getMessage(), ex);
				}

				DriverModel d = new DriverModel();
				d.setPlateNo(vd.getPlateNo());
				d.setPlateColor(vd.getPlateColor());
				d.setDriverId("410105197709212130");
				d.setDriverName(driverData.getDriverName());
				d.setLicense(driverData.getCertificationCode());
				d.setOrgName(driverData.getAgencyName());
				// 主动上报驾驶员信息
				this.transferGpsService.transferDriverInfo(d);

			}
			// this.baseDao.save(rd);
		}

	}

	// *
	// * 保存行车记录仪采集上来的数据
	//
	// private HashMap msgMap = new HashMap();
	// T808Message mymsg = null;
	// List<Byte> bytes = new ArrayList<Byte>();
	Map<String, List<T808Message>> vehicleRecorderDataMap = new HashMap();

	private void SaveVehicleRecorder(T808Message msg) {
		T808MessageHeader header = msg.getHeader();
		logger.error("是否分包:" + header.getIsPackage() + ",分包号:"
				+ header.getMessagePacketNo() + ",分包:"
				+ header.getMessageTotalPacketsCount());
		JT_0700 rd = null;
		if (header.getIsPackage()) {
			int packetNo = header.getMessagePacketNo();
			int totalPacketNo = header.getMessageTotalPacketsCount();
			String key = msg.getSimNo() + "_"
					+ msg.getHeader().getMessageType();
			List<T808Message> ls = null;
			if (packetNo == 1) {
				ls = new ArrayList();
				ls.add(msg);
				vehicleRecorderDataMap.put(key, ls);
			} else {
				ls = vehicleRecorderDataMap.get(key);
				if (ls != null)
					ls.add(msg);
			}
			if (packetNo == totalPacketNo) {
				ls = vehicleRecorderDataMap.get(key);
				byte[] bytes = new byte[10240];
				int m = 0;
				for (T808Message mg : ls) {
					byte[] b = null;
					if (mg.getMessageContents() != null) {
						rd = (JT_0700) mg.getMessageContents();
						b = rd.getCmdData();
					} else
						b = mg.getChildPacket();
					System.arraycopy(b, 0, bytes, m, b.length);
					m += b.length;
				}
				byte[] cmdData = new byte[m];
				System.arraycopy(bytes, 0, cmdData, 0, m);
				rd.setCmdData(cmdData);
			}
		} else {
			rd = (JT_0700) msg.getMessageContents();
		}
		if (rd == null || msg.getHeader() == null)
			return;

		VehicleData vd = this.realDataService.getVehicleData(msg.getSimNo());
		if (vd == null)
			return;

		// 响应流水号
		int resNo = rd.getResponseMessageSerialNo();
		IRecorderDataBlock recorderData = rd.getData();
		TerminalCommand tc = terminalCommandService.getCommandBySn(resNo);
		if (tc == null)
			tc = commandParseService.getLatestCommand(
					JT808Constants.CMD_VEHICLE_RECORDER, vd.getSimNo());
		long commandId = 0;
		if (tc != null) {
			commandId = tc.getEntityId();
			tc = commandParseService.UpdateStatus(msg.getSimNo(), tc.getSN(),
					TerminalCommand.STATUS_SUCCESS);
			if (TerminalCommand.FROM_GOV.equals(tc.getOwner())) {
				// 如果是上级平台下发的指令，则需要转发给上级平台
				this.transferGpsService.transferRecorderData(vd.getPlateNo(),
						vd.getPlateColor(), rd.getCommandWord(),
						rd.getCmdData());
			}

		}
		List result = new ArrayList();
		byte cmdWord = recorderData.getCommandWord();
		logger.error(cmdWord + ',' + recorderData.toString());
		if (cmdWord == 0x05) {
			Recorder_SpeedIn360Hours dv = (Recorder_SpeedIn360Hours) recorderData;
			for (Date key : dv.getSpeedsIn360Hours().keySet()) {
				byte[] values = dv.getSpeedsIn360Hours().get(key);
				StringBuilder sb = new StringBuilder();
				int m = 0;
				for (byte b : values) {
					VehicleRecorder vr1 = new VehicleRecorder();
					vr1.setCmd(cmdWord);
					vr1.setCommandId(commandId);
					vr1.setStartTime(key);
					vr1.setSpeed(b);
					vr1.setSortId(m++);
					vr1.setVehicleId(vd.getEntityId());
					result.add(vr1);
				}
			}

		} else if (cmdWord == 0x07) {
			Recorder_DoubtfulPointData dv = (Recorder_DoubtfulPointData) recorderData;
			for (Date key : dv.getDoubtfulPointData().keySet()) {
				ArrayList<Byte[]> values = dv.getDoubtfulPointData().get(key);
				StringBuilder sb = new StringBuilder();
				int m = 0;
				for (Byte[] b : values) {
					VehicleRecorder vr1 = new VehicleRecorder();
					vr1.setCmd(cmdWord);
					vr1.setCommandId(commandId);
					vr1.setStartTime(key);
					vr1.setSpeed(b[0]);
					vr1.setSignal(b[1]);
					vr1.setSortId(m++);
					vr1.setVehicleId(vd.getEntityId());
					result.add(vr1);
				}
			}

		} else if (cmdWord == 0x09) {
			// 最近两天内的数据
			Recorder_SpeedIn2Days dv = (Recorder_SpeedIn2Days) recorderData;
			for (Date key : dv.getSpeedsIn2Days().keySet()) {
				byte[] values = dv.getSpeedsIn2Days().get(key);
				StringBuilder sb = new StringBuilder();
				int m = 0;
				for (byte b : values) {
					VehicleRecorder vr1 = new VehicleRecorder();
					vr1.setCmd(cmdWord);
					vr1.setCommandId(commandId);
					vr1.setStartTime(key);
					vr1.setSpeed(b);
					vr1.setSortId(m++);
					vr1.setVehicleId(vd.getEntityId());
					result.add(vr1);
				}
			}

		} else if (cmdWord == 0x11) {
			// 疲劳驾驶
			Recorder_TiredDrivingRecord dv = (Recorder_TiredDrivingRecord) recorderData;
			int m = 0;
			for (TiredDrivingRecordItem ti : dv.getRecords()) {
				VehicleRecorder vr1 = new VehicleRecorder();
				vr1.setCmd(cmdWord);
				vr1.setCommandId(commandId);
				vr1.setStartTime(ti.getStartTime());
				vr1.setEndTime(ti.getEndTime());
				// vr1.setCmdData(ti.getDriverLincenseNo())；
				vr1.setSortId(m++);
				vr1.setVehicleId(vd.getEntityId());
				result.add(vr1);
			}
		} else {
			VehicleRecorder vr1 = new VehicleRecorder();
			vr1.setCmd(cmdWord);
			vr1.setCommandId(commandId);
			vr1.setVehicleId(vd.getEntityId());
			vr1.setCmdData(recorderData.toString());
			result.add(vr1);
		}

		this.vehicleRecorderService.saveOrUpdateAll(result);

	}

	// *
	// * 接收上传的媒体信息数据，是终端自动发送
	//
	private void SaveMediaInfo(T808Message msg) {
		JT_0800 uploadMediaMsg = (JT_0800) msg.getMessageContents();

		MediaItem mi = new MediaItem();
		mi.setCodeFormat(uploadMediaMsg.getMultidediaCodeFormat());
		mi.setMediaDataId((int) uploadMediaMsg.getMultimediaDataId());
		mi.setMediaType(uploadMediaMsg.getMultimediaType());
		mi.setChannelId(uploadMediaMsg.getChannelId());
		mi.setEventCode(uploadMediaMsg.getEventCode());
		mi.setSimNo(msg.getHeader().getSimId());
		mi.setPlateNo(msg.getPlateNo());
		mi.setCommandType(MediaItem.INFO); // 根据上传命令的应答

		try {
			// 记录下上传的文件列表，便于检索
			this.mediaItemService.saveOrUpdate(mi);

			TerminalCommand tc = new TerminalCommand();
			tc.setCmdType(msg.getHeader().getMessageType());
			tc.setSN(msg.getHeader().getMessageSerialNo());
			tc.setSimNo(msg.getSimNo());
			VehicleData vd = this.realDataService.getVehicleData(tc.getSimNo());
			if (vd != null) {
				tc.setPlateNo(vd.getPlateNo());
				tc.setVehicleId(vd.getEntityId());
			}
			tc.setCmdData(uploadMediaMsg.toString());
			tc.setOwner(TerminalCommand.FROM_TERMINAL);
			tc.setUpdateDate(new Date());
			tc.setStatus(TerminalCommand.STATUS_SUCCESS);

			this.terminalCommandService.save(tc);
		} catch (RuntimeException ex) {
			logger.error(ex.getMessage());
			logger.error(ex.getStackTrace());
		}
	}

	// *
	// * 接收终端返回的媒体媒体检索数据
	//
	private void SaveMediaSearchItem(T808Message msg) {
		JT_0802 msgData = (JT_0802) msg.getMessageContents();
		// 得到返回的响应号
		int sn = msgData.getResponseMessageSerialNo();
		// 更新下发命令的返回状态，确定终端已成功应答
		TerminalCommand tc = terminalCommandService.getCommandBySn(sn);// (TerminalCommand)this.baseDao.find(hsql,
		// resNo);
		long commandId = 0;
		if (tc != null) {
			commandId = tc.getEntityId();
		}

		for (MuldimediaSearchDataItem uploadMediaMsg : msgData.getDataItems()) {
			MediaItem mi = new MediaItem();
			mi.setMediaDataId((int) uploadMediaMsg.getMultimediaId());
			mi.setMediaType(uploadMediaMsg.getMultimediaType());
			mi.setChannelId(uploadMediaMsg.getChannelId());
			mi.setEventCode(uploadMediaMsg.getEventCode());
			mi.setSimNo(msg.getHeader().getSimId());
			mi.setCommandId(commandId);
			mi.setPlateNo(msg.getPlateNo());
			// mi.setCommandId(tc.getEntityId()); //记录下命令ID，可以根据命令来查询应答
			Date dt = DateUtil.stringToDatetime(uploadMediaMsg.getPosition()
					.getTime(), "yyyyMMddHHmmss");
			if (dt == null) {
				dt = new Date();
				logger.error("媒体数据时间解析错误"
						+ uploadMediaMsg.getPosition().getTime());
			}
			mi.setSendTime(dt); // 取自位置时间

			mi.setCommandType(MediaItem.UPLOAD); // 根据上传命令的应答
			try {
				// 记录下上传的文件列表，便于检索
				this.mediaItemService.saveOrUpdate(mi);
			} catch (RuntimeException ex) {
				logger.error(ex.getMessage(), ex);
			}
		}
		if (tc != null) {
			commandParseService.UpdateStatus(msg.getSimNo(), sn,
					TerminalCommand.STATUS_SUCCESS);
		}
	}

	public Boolean getEnableSaveDb() {
		return enableSaveDb;
	}

	public void setEnableSaveDb(Boolean enableSaveDb) {
		this.enableSaveDb = enableSaveDb;
	}

	public IMediaService getMediaService() {
		return mediaService;
	}

	public void setMediaService(IMediaService mediaService) {
		this.mediaService = mediaService;
	}

	public boolean isTransparentTransport() {
		return transparentTransport;
	}

	public void setTransparentTransport(boolean transparentTransport) {
		this.transparentTransport = transparentTransport;
	}

	public IBatchInsertService getBatchInsertService() {
		return batchInsertService;
	}

	public void setBatchInsertService(IBatchInsertService batchInsertService) {
		this.batchInsertService = batchInsertService;
	}

	public boolean isEnableDriverInfoUpload() {
		return enableDriverInfoUpload;
	}

	public void setEnableDriverInfoUpload(boolean enableDriverInfoUpload) {
		this.enableDriverInfoUpload = enableDriverInfoUpload;
	}

	public boolean isEnableEWayBillUpload() {
		return enableEWayBillUpload;
	}

	public void setEnableEWayBillUpload(boolean enableEWayBillUpload) {
		this.enableEWayBillUpload = enableEWayBillUpload;
	}

}